package com.fjh.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fjh.domain.UserAddr;
import com.fjh.mapper.UserAddrMapper;
import com.fjh.service.UserAddrService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("p/address")
@Api(tags = "用户收货地址管理")
public class UserAddrController {

    @Autowired
    private UserAddrService userAddrService;

    @GetMapping("list")
    @ApiOperation("查询用户的所有收货地址")
    public ResponseEntity<List<UserAddr>> userAllAddr(){
        String userId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        List<UserAddr> userAddrs = userAddrService.getUserAllAddr(userId);
        return ResponseEntity.ok(userAddrs);
    }

    @GetMapping("addAddr")
    @ApiOperation("新增用户的收货地址")
    public ResponseEntity<Void> addUserAddr(@RequestBody UserAddr userAddr){
        String userId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        userAddr.setUserId(userId);
        userAddrService.save(userAddr);
        return ResponseEntity.ok().build();
    }

    @PutMapping("defaultAddr/{id}")
    @ApiOperation("修改用户的默认收货地址")
    public ResponseEntity<Void> updateDefaultAddr(@PathVariable ("id")Long id){
        String userId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        userAddrService.changeUserDefaultAddr(userId,id);
        return ResponseEntity.ok().build();
    }

    //----------------------------------

    /**
     * 远程调用   获取用户的默认收货地址
     * @param userId
     * @return
     */
    @GetMapping("getUserDefaultAddr")
    @ApiOperation("获取用户的默认收货地址")
    UserAddr getUserDefaultAddr(@RequestParam String userId){
        return userAddrService.getOne(new LambdaQueryWrapper<UserAddr>()
                .eq(UserAddr::getUserId,userId)
                .eq(UserAddr::getCommonAddr,1)
                .eq(UserAddr::getStatus,1)
        );
    }


}
